package com.joymart.dictionary;

import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;

@RestController
public class DictionaryController {

    @Autowired
    private DictionaryService dictionaryService;

    @GetMapping("/dictionaries/{name}")
    public Object getDictionary(@PathVariable String name){
        Dictionary dict = dictionaryService.findByName(name);
        if(dict == null){
            throw  new JoymartBusinessException("参数错误");
        }
        return dict.getKeyValues();
    }

    /**
     * 维护字典项
     * @param name
     * @return
     */
    @PutMapping("/admin/dictionaries/{name}")
    public void maintainDictionary(@PathVariable String name, @RequestBody LinkedHashMap<String, Dictionary.Value> items){
        SecurityUtils.requiresRestAuthority("SystemSettings");
        Dictionary dict = new Dictionary();
        dict.setName(name);
        dict.setKeyValues(items);
        dictionaryService.maintainDictionary(dict);
    }
}
